import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { MessageTemplate } from './message-template.entity';

@Injectable()
export class MessageTemplateService {
  constructor(
    @InjectRepository(MessageTemplate)
    private messageTemplateRepository: Repository<MessageTemplate>,
  ) { }

  async findAll(userId?: number): Promise<MessageTemplate[]> {
    // 获取所有模板，或者特定用户的模板
    const where = userId ? { userId } : {};
    try {
      const templates = await this.messageTemplateRepository.find({ where });

      // 确保所有字段都有有效值
      return templates.map(template => {
        // 创建一个新对象，避免修改实体对象的类型
        const formattedTemplate: any = {
          ...template,
          title: template.title || template.name || '',
          name: template.name || '',
          content: template.content || '',
          msgType: template.msgType || 'text',
          remark: template.remark || '',
        };

        // 格式化日期
        formattedTemplate.createDateString = template.createDate
          ? template.createDate.toISOString()
          : new Date().toISOString();
        formattedTemplate.updateDateString = template.updateDate
          ? template.updateDate.toISOString()
          : new Date().toISOString();

        return formattedTemplate;
      });
    } catch (error) {
      console.error('Error fetching message templates:', error);
      return []; // 返回空数组而不是抛出错误
    }
  }

  async findOne(id: number): Promise<MessageTemplate> {
    const template = await this.messageTemplateRepository.findOne({ where: { id } });

    if (template) {
      // 添加格式化的字符串日期，但不修改原始Date类型
      (template as any).title = template.title || template.name || '';
      (template as any).msgType = template.msgType || 'text';
      (template as any).createDateString = template.createDate
        ? template.createDate.toISOString()
        : new Date().toISOString();
      (template as any).updateDateString = template.updateDate
        ? template.updateDate.toISOString()
        : new Date().toISOString();
    }

    return template;
  }

  async create(createTemplateDto: any): Promise<MessageTemplate> {
    const template = new MessageTemplate();
    template.title = createTemplateDto.title || '';
    template.name = createTemplateDto.name || createTemplateDto.title || '';
    template.content = createTemplateDto.content;
    template.msgType = createTemplateDto.msgType || 'text';
    template.remark = createTemplateDto.remark || '';
    template.userId = createTemplateDto.userId;

    return this.messageTemplateRepository.save(template);
  }

  async update(id: number, updateTemplateDto: any): Promise<MessageTemplate> {
    await this.messageTemplateRepository.update(id, updateTemplateDto);
    return this.messageTemplateRepository.findOne({ where: { id } });
  }

  async remove(id: number): Promise<void> {
    await this.messageTemplateRepository.delete(id);
  }
} 